package com.qf.controller;/*
 *保护你的大熊
 *2021/11/17
 *20:27
 */

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller
@RequestMapping("/upload")
public class UploadController {

    /**
     * 跳转到文件上传页面
     * @return
     */
    @RequestMapping("/file")
    public String toFileUpload(){
        return "jsp/fileupload";
    }

    /**
     * 上传
     * @param source
     * @return
     * @throws Exception
     */
    @RequestMapping("/test1")
    @ResponseBody
    public String test1(MultipartFile source) throws Exception{
        //完整文件名
        String filename = source.getOriginalFilename();
        //文件大小
        long size = source.getSize();

        System.out.println("============" + filename);
        System.out.println("============" + size);

        File filedir = new File("E:\\ideaWorkspace\\workspace2107\\springmvcDemo01\\target\\springmvcDemo01-1.0-SNAPSHOT\\upload\\");

        //判断目录中的文件夹如果不存在则自动创建
        if(!filedir.exists()){
            filedir.mkdirs();
        }

        File file = new File(filedir +"/"+ filename);

        //将文件存储到指定目录中
        source.transferTo(file);

        return "http://localhost:8080/update/" + filename;
    }

    /**
     * 下载
     * @param name
     * @param session
     * @param response
     * @throws IOException
     */
    @RequestMapping("/test2")
    public void test2(String name, HttpSession session, HttpServletResponse response) throws IOException {

        String realPath = session.getServletContext().getRealPath("/upload");
        String filePath = realPath+"\\"+name;

        //设置响应头  告知浏览器，要以附件的形式保存内容   filename=浏览器显示的下载文件名
        response.setHeader("content-disposition","attachment;filename="+name);

        // 响应
        IOUtils.copy(new FileInputStream(filePath), response.getOutputStream());

        //return null;
    }
}
